package cn.jekun.web.shop.service;

import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.D;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.bean.Member;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.McMemberService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.web.shop.bean.ShopMember;

/**
 * 会员查询Service
 * @author
 *
 */
@Service(MemberService.BEAN_NAME)
public class MemberService extends ShopBaseService{
	public static final String BEAN_NAME="cn.jekun.web.shop.service.MemberService";
	@Override
	public String getNamespace() {
		// TODO Auto-generated method stub
		return "ACTION_MC_MEMBER";
	}
	@Resource(name=RsUserService.BEAN_NAME)
	protected RsUserService rsUserService;
	@Resource(name=McMemberService.BEAN_NAME)
	protected McMemberService memberService;

	/**
	 * 获取商家会员
	 * @param map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List<ShopMember> getShopMembers(@McMember.AnnoMemberTypeId String memberType,
										   @McMember.AnnoMemberId String memberId,
//										   @RsUser.AnnoMobile String mobile,
										   @Security String mobile,
										   @RsUser.AnnoUserName String username,
										   @RsUser.AnnoRealName String realname,
										   @D String beginDate,
										   @D String endDate,
										   @Num(length=10,message="输入的开始积分非法") String beginCredits,
										   @Num(length=10,message="输入的结束积分非法") String endCredits,
										   @RsUser.AnnoShopId String shopId,
										   @Security String source,
										   Page page){

		String SQL ="";
		if(!"".equals(beginDate) && "".equals(endDate)){
			SQL +=" and a.create_time"
					+ ">= to_date('"+beginDate.toString()+"','yyyy/MM/dd hh24:mi:ss')";
		}
		if("".equals(beginDate) && !"".equals(endDate)){
			SQL +=" and a.create_time"
					+ "<= to_date('"+endDate.toString()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}
		if(!"".equals(beginDate) && beginDate!=null 
				&& !"".equals(endDate) && endDate!=null){
			SQL +=" and a.create_time"
					+ ">= to_date('"+beginDate.toString()+"','yyyy/MM/dd hh24:mi:ss')"
					+ " and a.create_time "
					+ "<= to_date('"+endDate.toString()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginCredits) && "".equals(endCredits)){
			SQL +=" and a.credits"
					+ ">= '"+beginCredits.toString()+"'";
		}
		if("".equals(beginCredits) && !"".equals(endCredits)){
			SQL +=" and a.credits"
					+ "<= '"+endCredits.toString()+"'";
		}
		if(!"".equals(beginCredits) && beginCredits!=null 
				&& !"".equals(endCredits) && endCredits!=null){
			SQL +=" and a.credits"
					+ ">= '"+beginCredits.toString()+"'"
					+ " and a.credits "
					+ "<= '"+endCredits.toString()+"'";
		}
		if(memberType!=null && !"".equals(memberType)){
			SQL +=" and a.level_id = '"+memberType+"'"; 
		}
		if(mobile!=null && !"".equals(mobile)){
			SQL +=" and b.mobile like '%"+mobile+"%'"; 
		}
		if(realname!=null && !"".equals(realname)){
			SQL +=" and b.REAL_NAME like '%"+realname+"%'"; 
		}
		if(username!=null && !"".equals(username)){
			SQL +=" and b.USER_NAME like '%"+username+"%'"; 
		}
		if("showNotInStaffMember".equals(source)){
			SQL +=" and not exists (select 1 from rs_user_shop us where us.shop_id = '"+shopId+"' and us.user_id=a.user_id)";
//			SQL +=" and b.status = '1'";
		}
		
		Map map=new HashMap();
		map.put("shopId", shopId);
		SqlUtis.prepareSql(map,SQL);
		return this.list(this.getStatementName("list"),map,page);
	}

	/**
	 * 增加会员
	 * @return
	 */
	@Transactional
	@SuppressWarnings("rawtypes")
	public boolean addMember(String userName,
							 String password,
							 String identifyTypeId,
							 String identity,
							 String card,
							 String email,
							 String mobile,
							 String phoneNumber,
							 String realName,
							 String address,
							 String sex,
							 String shopId,
							 String memberlevel,
							 String memoName,
							 String memberType){
		
		RsUser rsUser = new RsUser();
		rsUser.setUserName(userName);
		rsUser.setPassword(password);
		rsUser.setIdentifyTypeId(identifyTypeId);
		rsUser.setIdentity(identity);
		rsUser.setCard(card);
		rsUser.setEmail(email);
		rsUser.setMobile(mobile);
		rsUser.setPhoneNumber(phoneNumber);
		rsUser.setRealName(realName);
		rsUser.setAddress(address);
		rsUser.setSex(sex);
		rsUser.setShopId(shopId);
		McMember mcMember = new McMember();
		mcMember.setLevelId(memberlevel);
		mcMember.setShopId(shopId);
		mcMember.setMemoName(memoName);
		mcMember.setLevelId(memberType);
		mcMember.setMemberTypeId("2");
		mcMember.setCredits(0.0);
		
		Map formMap=new HashMap<String, String>();
		formMap.put("mcMember", mcMember);
		formMap.put("rsUser", rsUser);
		
		String userId = this.insert(this.getStatementName("insertuser"),formMap).toString();
		if(userId!=null){
			if(this.userisShopId(userId,mcMember.getShopId())){
				return false;
			}
			mcMember.setUserId(userId);
			this.insert(this.getStatementName("insertmember"),formMap);
		}
		return true;
	}

	/**
	 * 判断当前用户是否存在
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean isexistsUser(@RsUser.AnnoUserName String userName){

		RsUser rsUser = new RsUser();
		rsUser.setUserName(userName);
		Map map = new HashMap();
		map.put("rsUser", rsUser);
		map.put(RsUser.COL_USER_NAME, userName);
		SqlUtis.prepareSql(map,
				SqlUtis.getSQL(map, "a."+RsUser.COL_USER_NAME, Types.VARCHAR));
		return rsUserService.exists(map);
	}

	/**
	 * 判断当前手机号码是否存在
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean isexistsMobile(@RsUser.AnnoMobile String mobile){

		RsUser rsUser = new RsUser();
		rsUser.setMobile(mobile);
		Map map = new HashMap();
		map.put("rsUser", rsUser);
		map.put(RsUser.COL_MOBILE, mobile);
		SqlUtis.prepareSql(map,
				SqlUtis.getSQL(map, "a."+RsUser.COL_MOBILE, Types.VARCHAR));
		return rsUserService.exists(map);
	}

	/**
	 * 判断当前邮箱是否存在
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean isexistsEmail(@RsUser.AnnoEmail String email){

		RsUser rsUser = new RsUser();
		rsUser.setMobile(email);
		Map map = new HashMap();
		map.put("rsUser", rsUser);
		map.put(RsUser.COL_EMAIL, email);
		SqlUtis.prepareSql(map,
				SqlUtis.getSQL(map, "a."+RsUser.COL_EMAIL, Types.VARCHAR));
		return rsUserService.exists(map);
	}

	/**
	 * 判断当前商家是否已存在该会员
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean userisShopId(String userId,String shopId){

		Map queryMap = new HashMap();
		queryMap.put(Member.COL_SHOP_ID,shopId);
		queryMap.put(Member.COL_USER_ID,userId);
		SqlUtis.prepareSql(queryMap
				,SqlUtis.getSQL(queryMap, "a."+Member.COL_SHOP_ID, Types.VARCHAR,SqlUtis.EQ)
				,SqlUtis.getSQL(queryMap, "a."+Member.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));

		return memberService.exists(queryMap);

	}


	/**
	 * 会员详情
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ShopMember getMemberDetails(@RsUser.AnnoUserId String userId,@RsUser.AnnoShopId String shopId){

		try{
			Map queryMap = new HashMap();
			queryMap.put("userId", userId);
			queryMap.put("shopId", shopId);
			return this.one(getStatementName("details"), queryMap);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/**
	 * 修改会员详情
	 * @return
	 * @throws ParseException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public int update(@RsUser.AnnoUserId String userId,
					  @RsUser.AnnoSex String sex,
					  @RsUser.AnnoCard String card,
					  @RsUser.AnnoPhoneNumber String phoneNumber,
					  @RsUser.AnnoEmail String email,
					  @RsUser.AnnoMobile String mobile,
					  @RsUser.AnnoRealName String realName,
					  @RsUser.AnnoAddress String address,
					  @RsUser.AnnoBirthday String birthday) throws ParseException{
		
		RsUser rsUser=new RsUser();
		rsUser.setUserId(userId);
		rsUser.setSex(sex);
		rsUser.setCard(card);
		rsUser.setPhoneNumber(phoneNumber);
		rsUser.setEmail(email);
		rsUser.setMobile(mobile);
		rsUser.setRealName(realName);
		rsUser.setAddress(address);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		rsUser.setBirthday(sdf.parse(birthday));
		
		Map formMap=new HashMap<String, String>();
		formMap.put("rsUser", rsUser);
		formMap.put(RsUser.COL_USER_ID,userId);
		SqlUtis.prepareSql(formMap
				, SqlUtis.getSQLRequired(formMap,RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ)
				);

		return rsUserService.update(formMap);
	}

	/**
	 * 营销短信发送
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean sendMarkeSms(@RsUser.AnnoShopId String shopId,@Security String smsContent){

		//获取当前商家的所有会员
		Map map = new HashMap();
		map.put("shopId",shopId);
		List<ShopMember> list = this.list(map);
		for (int i = 0; i < list.size(); i++) {

			if(StringUtils.isNotBlank(list.get(i).getMobile())){
	           //调用发送短信接口 
			}
		}

		return true;

	}

}
